package com.moyv.schoolbbs.ui.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.moyv.schoolbbs.R;
import com.moyv.schoolbbs.bean.UserInfo;
import com.moyv.schoolbbs.config.AccountConstant;
import com.moyv.schoolbbs.config.PictureSelectorConfig;
import com.moyv.schoolbbs.service.ChangeService;
import com.moyv.schoolbbs.service.UserInfoService;
import com.moyv.schoolbbs.ui.activity.BottomTabLayoutActivity;
import com.moyv.schoolbbs.ui.activity.LoginActivity;
import com.moyv.schoolbbs.ui.activity.ManagerActivity;
import com.moyv.schoolbbs.ui.view.MaskImageView;
import com.moyv.schoolbbs.ui.view.MeItemView;
import com.moyv.schoolbbs.ui.view.popWindow.PopItemAction;
import com.moyv.schoolbbs.ui.view.popWindow.window.PopWindow;
import com.moyv.schoolbbs.util.ToastUtils;

import static com.moyv.schoolbbs.config.AccountConstant.LOGIN;
import static com.moyv.schoolbbs.config.PictureSelectorConfig.initCamer;
import static com.moyv.schoolbbs.config.URLConstant.HEAD_URL;
import static com.moyv.schoolbbs.service.MainService.STAR_POSTS;
import static com.moyv.schoolbbs.service.MainService.USER_POSTS;
import static com.moyv.schoolbbs.util.AnalysisUtils.cleanLoginStatus;
import static com.moyv.schoolbbs.util.AnalysisUtils.readLoginStatus;
import static com.moyv.schoolbbs.util.ToastUtils.show;

/**
 * @author moyv
 */
public class MeFragment extends Fragment implements View.OnClickListener {
    private Context context;
    private ImageView ivHead;
    private MaskImageView ivBackground;
    private TextView tvName;
    private Button btnLogin;
    private Button btnLogOut;
    private MeItemView itemName;
    private MeItemView itemAccount;
    private MeItemView itemIntroduction;
    private MeItemView postManager;
    private MeItemView starManager;
    private AlertDialog changeDialog;


    private BottomTabLayoutActivity activity;


    public static MeFragment newInstance(String title) {
        Bundle arguments = new Bundle();
        arguments.putString("TITLE", title);
        MeFragment fragment = new MeFragment();
        fragment.setArguments(arguments);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_me, container, false);
        this.context = root.getContext();
        ivHead = root.findViewById(R.id.h_head);
        ivBackground = root.findViewById(R.id.h_background);
        tvName = root.findViewById(R.id.user_name);
        btnLogin = root.findViewById(R.id.btn_login);
        btnLogOut = root.findViewById(R.id.btn_log_out);
        itemName = root.findViewById(R.id.me_item_name);
        itemAccount = root.findViewById(R.id.me_item_account);
        itemIntroduction = root.findViewById(R.id.me_item_introduction);
        ivHead.setImageResource(R.drawable.login_head);

        activity = (BottomTabLayoutActivity) getActivity();

        btnLogOut.setOnClickListener(this);

        //严格模式，解决7.0拍照问题
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            builder.detectFileUriExposure();
        }

        ivHead = root.findViewById(R.id.h_head);
        ivBackground = root.findViewById(R.id.h_background);
        tvName = root.findViewById(R.id.user_name);
        btnLogin = root.findViewById(R.id.btn_login);
        btnLogOut = root.findViewById(R.id.btn_log_out);
        itemName = root.findViewById(R.id.me_item_name);
        itemAccount = root.findViewById(R.id.me_item_account);
        itemIntroduction = root.findViewById(R.id.me_item_introduction);
        ivHead.setImageResource(R.drawable.login_head);
        postManager = root.findViewById(R.id.me_tv_posts);
        starManager = root.findViewById(R.id.me_tv_stars);
        btnLogOut.setOnClickListener(this);
        btnLogin.setOnClickListener(this);
        itemName.setOnClickListener(this);
        itemIntroduction.setOnClickListener(this);
        postManager.setOnClickListener(this);
        starManager.setOnClickListener(this);
        ivHead.setOnClickListener(this);
        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        SharedPreferences sharedPreferences = context.getSharedPreferences("login", 0);
        if (readLoginStatus(context)) {
            tvName.setVisibility(View.VISIBLE);
            btnLogin.setVisibility(View.GONE);
            int account = sharedPreferences.getInt("account", 0);

//            高斯模糊背景
            Glide.with(context).load(HEAD_URL + account + ".jpg")
                    //缓存
//                    .signature( new ObjectKey(HEAD_SIG))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .apply(ivBackground.setGaussBlur())
                    //淡入淡出
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .into(ivBackground);

//            圆形头像加载
            Glide.with(context).load(HEAD_URL + account + ".jpg")
                    .error(R.drawable.login_head)
//                    .signature( new ObjectKey(HEAD_SIG))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(ivHead);

            UserInfoService userInfoService = new UserInfoService();
            new AccountConstant(context);
            userInfoService.getUserInfo(account, handler);
            itemAccount.setData(String.valueOf(account));
            //chat登录
            if (activity.getChatService() != null && !(account+"").equals(activity.getChatService().getId())) {
                System.out.println("重新登录！");
                if (!activity.getChatService().checkOutLogin(String.valueOf(account), sharedPreferences.getString("password", ""))) {
                    ToastUtils.showToast(context, "通信服务连接错误，请尝试重新登录，否则将无法使用通信功能！", true);
//                    AlertDialog.Builder builder=new AlertDialog.Builder(context);
//                    builder.set
//                    builder.show();
                }
            }
        } else {
//            退出登录操作
            tvName.setVisibility(View.GONE);
            btnLogin.setVisibility(View.VISIBLE);
            ivBackground.setImageBitmap(null);
            Glide.with(context).load(R.drawable.login_head)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(ivHead);
            itemName.setData("");
            itemAccount.setData("");
            itemIntroduction.setData("");

            //退出chat登录
            if (activity.getChatService() != null) {
                activity.getChatService().logout();
                activity.getChatService().setId("");
            }
        }
    }


    //    获取用户信息
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 200:
                    UserInfo userInfo = (UserInfo) msg.obj;
                    tvName.setText(userInfo.getName());
                    itemName.setData(userInfo.getName());
                    itemIntroduction.setData(userInfo.getIntroduction());
                    break;
                case 404:
                    show("登录失败，请重新登录");
                    cleanLoginStatus(context);
                    break;
                default:
                    System.out.println("返回错误信息");
            }
            return false;
        }
    });

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_log_out:
                cleanLoginStatus(context);
                new AccountConstant(context);
                if (!LOGIN) {
                    onResume();
                }
                break;
            case R.id.me_item_name:
                dialog(1, "请输入要修改的名字");
                break;
            case R.id.me_item_introduction:
                dialog(2, "请输入要修改的简介");
                break;
            case R.id.me_tv_stars:
                intentPostsManager(STAR_POSTS);
                show("点赞管理");
                break;
            case R.id.h_head:
                showPopWindow();
                break;
            default:
                System.out.println("点击事件没有执行事件");
        }
    }

    public void dialog(int index, String hint) {
        final EditText et = new EditText(context);
        et.setHint(hint);
//        et.setText(itemName.getData().getText().toString());
        changeDialog = new AlertDialog.Builder(context).setTitle("请输入消息")
                .setIcon(android.R.drawable.sym_def_app_icon)
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //按下确定键后的事件
                        ChangeService changeService = new ChangeService();
                        changeService.changeInfo(index, et.getText().toString(), handler1);
                    }
                }).setNegativeButton("取消", null).show();
    }

    Handler handler1 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 200:
                    onResume();
                    break;
                default:
            }
            return false;
        }
    });

    public void intentPostsManager(int type) {
        Intent intent = new Intent(context, ManagerActivity.class);
        intent.putExtra("type", type);
        startActivity(intent);
    }


    /**
     * popwindow选择拍照还是选择图片
     * 弹出选项框
     */
    private void showPopWindow() {
        PopWindow popWindow = new PopWindow.Builder((Activity) context)
//                .setStyle(PopWindow.PopWindowStyle.PopUp)
                .addItemAction(new PopItemAction("选择照片", PopItemAction.PopItemStyle.Normal, new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
//                        调用图片选择器，最多可以选中一张
                        PictureSelectorConfig.initMultiConfigCut((Activity) context);
                    }

                }))
                .addItemAction(new PopItemAction("拍照", PopItemAction.PopItemStyle.Warning, new PopItemAction.OnClickListener() {
                    @Override
                    public void onClick() {
//                        openCamera((Activity) context);
                        initCamer((Activity) context);
                    }
                }))
                .addItemAction(new PopItemAction("取消", PopItemAction.PopItemStyle.Cancel))
                .create();
        popWindow.show();
    }

}
